import smtplib
import time

import yaml
import os
from email.utils import formataddr
from email.message import EmailMessage


class Email:

    def __init__(self):
        self.msg = EmailMessage()
        config_path = get_config_path()
        config = load_config(config_path)
        self.smtp_server = config.get('smtp_server')
        self.smtp_port = config.get('smtp_port')
        self.username = config.get('username')
        self.password = config.get('password')
        self.sender = config.get('sender')
        self.receiver = config.get('receiver')
        self.subject = None
        self.message = None



    def set_subject(self, subject):
        """设置邮件主题"""
        self.subject = subject

    def set_message(self, message):
        """设置邮件内容"""
        #self.message = MIMEText(message, message_type, 'utf-8')
        self.message = message


    def set_receiver(self, receiver):
        """设置收件人"""
        self.receiver = receiver

    def send(self):
        """发送邮件"""
        if not self.subject or not self.message:
            print("错误：邮件主题或内容未设置。")
            return


        sender_name = 'AI'
        sender_email = self.sender
        self.msg['From'] = formataddr((sender_name, sender_email))
        self.msg['To'] = self.receiver
        self.msg['Subject'] = self.subject
        self.msg.set_content(self.message)
        try:
            # 连接到SMTP服务器
            server = smtplib.SMTP_SSL(self.smtp_server, self.smtp_port)
            # 登录到SMTP服务器
            server.login(self.username, self.password)
            # 发送邮件
            server.send_message(self.msg)
            print("邮件发送成功")
        except smtplib.SMTPConnectError as e:
            print('邮件发送失败，连接失败:', e.smtp_code, e.smtp_error)
        except smtplib.SMTPAuthenticationError as e:
            print('邮件发送失败，认证错误:', e.smtp_code, e.smtp_error)
        except smtplib.SMTPSenderRefused as e:
            print('邮件发送失败，发件人被拒绝:', e.smtp_code, e.smtp_error)
        except smtplib.SMTPRecipientsRefused as e:
            print('邮件发送失败，收件人被拒绝:', e.smtp_code, e.smtp_error)
        except smtplib.SMTPDataError as e:
            print('邮件发送失败，数据接收拒绝:', e.smtp_code, e.smtp_error)
        except smtplib.SMTPException as e:
            print('邮件发送失败, ', str(e))
        except Exception as e:
            print('邮件发送异常, ', str(e))
        finally:
            # 关闭连接
            server.quit()
def get_project_root():
    """获取项目根目录"""
    current_file = os.path.abspath(__file__)
    current_dir = os.path.dirname(current_file)
    root_dir = os.path.dirname(current_dir)
    return root_dir

def get_config_path():
    """获取配置文件路径"""
    root_dir = get_project_root()
    config_path = os.path.join(root_dir, 'mail.yaml')
    return config_path

def load_config(file_path):
    """从YAML配置文件加载设置"""
    try:
        with open(file_path, 'r', encoding='utf-8') as config_file:
            config = yaml.safe_load(config_file)
        return config
    except FileNotFoundError:
        print(f"错误：配置文件 {file_path} 未找到。")
        return None
    except yaml.YAMLError:
        print(f"错误：配置文件 {file_path} 格式不正确。")
        return None


if __name__ == "__main__":

    email = Email()
    email.set_subject("can test it")
    email.set_message("I wish to somebody")
    # 可选：覆盖收件人设置
    # email.set_receiver('another_receiver@example.com')
    email.send()
    time.sleep(2)
    email = Email()
    email.set_subject("can test it")
    email.set_message("I wish to somebody")
    # 可选：覆盖收件人设置
    # email.set_receiver('another_receiver@example.com')
    email.send()